package com.jly.config;

import com.jly.io.Resources;
import com.jly.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     *使用dom4j将配置文件进行解析，封装configuration
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {

        Document document = new SAXReader().read(inputStream);
        //<configuration>
        Element rootElement = document.getRootElement();
        List<Element> propertyElements = rootElement.selectNodes("//property");
        Properties properties = new Properties();

        for(Element properElement : propertyElements){
            String name = properElement.attributeValue("name");
            String value = properElement.attributeValue("value");
            properties.setProperty(name,value);
        }
        //连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        //填充configuration
        configuration.setDataSource(comboPooledDataSource);

        //mapper部分
        List<Element> mapperElements = rootElement.selectNodes("//mapper");

        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);

        for (Element mapperElement:mapperElements) {
            String mapperPath = mapperElement.attributeValue("resource");
            InputStream resourceAsInputStream = Resources.getResourceAsInputStream(mapperPath);
            xmlMapperBuilder.parseMapper(resourceAsInputStream);

        }
        return configuration;
    }

}
